package yunjiao.javatutorials.designpatterns.builder;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分步构建
 *
 * @author yangyunjiao
 */
public class UserStepBuilder {
    private UserStepBuilder() {
    }

    public static FirstNameBuilder newBuilder() {
        return new Builder();
    }

    // 接口定义构建阶段
    public interface FirstNameBuilder {
        LastNameBuilder firstName(String firstName);
    }

    public interface LastNameBuilder {
        OptionalBuilder lastName(String lastName);
    }

    public interface OptionalBuilder {
        OptionalBuilder age(int age);
        OptionalBuilder email(String email);
        OptionalBuilder phones(List<String> phones);
        OptionalBuilder phone(String phones);
        User build();
    }

    // 构建器实现
    private static class Builder implements FirstNameBuilder, LastNameBuilder, OptionalBuilder {
        private String firstName;
        private String lastName;
        private int age;
        private String email;
        private final List<String> phones = new ArrayList<>();

        private Builder() {
        }

        @Override
        public LastNameBuilder firstName(String firstName) {
            if (!StringUtils.hasText(firstName)) {
                throw new IllegalArgumentException("FirstName cannot be null or empty");
            }
            this.firstName = firstName;
            return this;
        }

        @Override
        public OptionalBuilder lastName(String lastName) {
            if (!StringUtils.hasText(lastName)) {
                throw new IllegalArgumentException("LastName cannot be null or empty");
            }
            this.lastName = lastName;
            return this;
        }

        @Override
        public OptionalBuilder age(int age) {
            this.age = age;
            return this;
        }

        @Override
        public OptionalBuilder email(String email) {
            this.email = email;
            return this;
        }

        @Override
        public OptionalBuilder phones(List<String> phones) {
            if (phones == null) {
                throw new IllegalArgumentException("Phones cannot be null");
            }
            this.phones.addAll(phones);
            return this;
        }

        @Override
        public OptionalBuilder phone(String phone) {
            if (!StringUtils.hasText(phone)) {
                throw new IllegalArgumentException("Phone cannot be null or empty");
            }
            this.phones.add(phone);
            return this;
        }

        @Override
        public User build() {
            return new User(firstName, lastName, age, email, phones);
        }
    }
}
